using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Waf.Applications;
using System.Windows;
using System.IO;
using System.Diagnostics;
using System.Windows.Threading;

namespace TrackMe.View
{
	public partial class App
	{
		//[Export(typeof(IConfig))]
		public IConfig CurrentConfig { get; set; }

		private CompositionContainer container;
		private ApplicationController controller;

		public App()
		{
			CurrentConfig = XmlConfig.LoadConfig();
		}

		public static App CurrentApp
		{
			get
			{
				return (App)Current;
			}
		}

		public void LogException(Exception ex)
		{
			EventLog.WriteEntry("TimeTracker", "ERROR: " + ex);
		}

		protected void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
		{
			e.Handled = true;
			if (MessageBox.Show("Something has gone wrong. " + e.Exception.Message + "\n" + e.Exception.StackTrace + ". Probably your last operation was not completed correctly. Do you want to leave the application?", "ERROR", MessageBoxButton.YesNo, MessageBoxImage.Error, MessageBoxResult.No) == MessageBoxResult.Yes)
			{
				// Make a backup of the database
				if (!CurrentConfig.UseRemoteConnection && File.Exists(CurrentConfig.LocalDatabasePath))
				{
					DateTime now = DateTime.Now;
					string suffix = now.Year + now.Month.ToString() + now.Day + now.Hour.ToString("00") + now.Minute.ToString("00") + now.Second.ToString("00");
					File.Copy(CurrentConfig.LocalDatabasePath, CurrentConfig.LocalDatabasePath + "." + suffix + ".crash.backup", true);
				}
				Shutdown();
			}
		}

		private void InitializeCompositionFramework()
		{
			var catalog = new AggregateCatalog();
			catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
			catalog.Catalogs.Add(new AssemblyCatalog(typeof(Controller).Assembly));
			catalog.Catalogs.Add(new AssemblyCatalog(typeof (ApplicationController).Assembly));
			catalog.Catalogs.Add(new AssemblyCatalog(typeof (Dao).Assembly));

			container = new CompositionContainer(catalog);
			var batch = new CompositionBatch();
			batch.AddExportedValue(container);
			container.Compose(batch);

			controller = container.GetExportedValue<ApplicationController>();
			controller.Run();
		}

		protected override void OnStartup(StartupEventArgs args)
		{
			base.OnStartup(args);

			#if (DEBUG != true)
            // Don't handle the exceptions in Debug mode because otherwise the Debugger wouldn't
            // jump into the code when an exception occurs.
            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
			#endif

			InitializeCompositionFramework();
			MainWindow.Show();
		}

	    public void GracefulShutDown()
		{
			Shutdown();
		}

		protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
		{
			GracefulShutDown();
			base.OnSessionEnding(e);
		}

	}
}
